<template>
  <el-dialog :title="title" :visible.sync="dialogVisible" width="60%">
    <!-- 表单 -->
    <el-form ref="ruleForm" :model="dataForm" :rules="dataRules" label-width="130px" class="data_info">
      <div class="dataInfo">
        <p>
          <span>基本信息</span>
        </p>
        <el-row>
          <el-col :span="10">
            <el-form-item label="公司名称" prop="companyName">
              <el-input v-if="disabledActive" v-model="companyNameVal" :disabled="disabledActive"></el-input>
              <el-autocomplete v-else clearable @clear="handleClear" style="width:100%" v-model="dataForm.companyName"
                :fetch-suggestions="querySearch" placeholder="请输入公司名称" :trigger-on-focus="false"
                @select="handleSelect"></el-autocomplete>
            </el-form-item>
          </el-col>
          <el-col :span="10">
            <el-form-item label="公司类型">
              <el-input v-model="companyTypeName" readonly disabled></el-input>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="10">
            <el-form-item label="填报人">
              <el-input v-model="filledByName" readonly disabled></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="10">
            <el-form-item label="填报人角色">
              <el-input v-model="filledByRole" readonly disabled></el-input>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="10">
            <el-form-item label="单位地址">
              <el-input v-model="companyAddress" readonly disabled></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="10">
            <el-form-item label="用水类型" prop="waterTypeId">
              <el-select v-model="dataForm.waterTypeId" placeholder="请选择" style="width:100%">
                <el-option v-for="item in waterTypeList" :key="item.id" :label="item.name" :value="item.id"></el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
      </div>
      <div class="dataInfo">
        <p>
          <span>用水情况</span>
        </p>
        <!-- 选择年份 -->
        <el-form-item label="选择年份" style="width:50%">
          <el-date-picker
            v-model="dataForm.year"
            type="year"
            :disabled="type !== 'new'"
            value-format="yyyy"
            placeholder="选择年份">
          </el-date-picker>
        </el-form-item>
        <!-- 选择季度 -->
        <el-form-item v-for="(month, index) in dynamicValidateForm.monthsList" label="选择月份" :key="index">
          <div style="display:flex">
            <el-select v-model="month.month" placeholder="请选择" clearable filterable style="width:10%;margin-right:10px">
              <el-option v-for="item in monthDataList" :key="item.month" :label="item.label"
                :value="item.month"></el-option>
            </el-select>
            <el-input v-model="month.water" clearable style="width:23%" placeholder="请输入用水量"></el-input>
            <el-button type="primary" @click="addMonth">新增</el-button>
            <el-button @click.prevent="removeMonth(month)"
              v-if="dynamicValidateForm.monthsList.length > 1">删除</el-button>
          </div>
        </el-form-item>
        <!-- 备注 -->
        <el-form-item label="备注" style="width:50%">
          <el-input type="textarea" :rows="4" placeholder="请输入内容" v-model="dataForm.remarks"></el-input>
        </el-form-item>
      </div>
    </el-form>
    <span slot="footer" class="dialog-footer" v-if="type !== 'info'">
      <el-button @click="dialogVisible = false">取 消</el-button>
      <el-button type="primary" @click="handleSubmit">确 定</el-button>
    </span>
  </el-dialog>
</template>

<script>
import { getAllCompany, getAllWaterType } from '@/api/base'
import {
  insertWaterSupervise,
  updateWaterSupervise,
  catWaterDeclareSuperviseById,
  getCompanyInfoByUserId,
} from '@/api/other'

import { monthData } from '@/config/dataList'
import { isRepeat } from '@/config/publicMethod'
export default {
  data() {
    return {
      dialogVisible: false,
      title: '',
      type: '',
      dataForm: {
        companyId: '',
        companyName: '',
        waterTypeId: '',
        insertWaterDeclareItemRequest: [],
        updateWaterDeclareItemRequest: [],
        remarks: '',
        year: '',
        id: '',
      },
      dataRules: {
        companyName: [
          { required: true, message: '请选择公司', trigger: 'change' },
        ],
        waterTypeId: [
          { required: true, message: '请选择用水类型', trigger: 'change' },
        ],
      },
      companyList: [],
      waterTypeList: [], // 用水类型
      companyAddress: '', // 公司地址
      companyTypeName: '', // 公司类型
      filledByName: '',
      filledByRole: '',

      disabledActive: false,

      dynamicValidateForm: {
        // 月份
        monthsList: [
          {
            month: '',
            water: '',
          },
        ],
      },
      // 季度
      monthDataList: monthData(),
      companyNameVal: '',
    }
  },
  mounted() { },
  methods: {
    async init(type, item) {
      this.dialogVisible = true
      this.title = type == 'new' ? '新增' : type == 'edit' ? '编辑' : '详情'
      this.type = type
      this.dataForm.id = item ? item.id : undefined
      const { name, roles } = this.$store.state.user.userObj
      const { nameZh } = roles[0]
      this.filledByName = name
      this.filledByRole = nameZh
      if (type == 'new') {
        // // 获取vuex中公司信息
        const { userObj } = this.$store.state && this.$store.state.user
        const { id } = userObj.roles[0] // 角色权限id
        const userId = userObj.id // 角色账号id
        if (id == '1' || id == '2') {
          //管理账号 普通账号
          this.dataRules.companyName[0].required = true
          this.disabledActive = false
          this.dataForm.companyId = ''
          this.dataForm.companyName = ''
          this.companyTypeName = ''
          this.companyAddress = ''
        } else {
          // 其他账号 (公司的角色id)
          let res = await this.getCompanyInfoByUserIdFun(userId)
          this.disabledActive = true
          this.dataForm.companyId = res.id
          this.companyNameVal = res.companyName
          this.companyTypeName = res.companyTypeResponse.companyTypeName
          this.companyAddress = res.companyAddress
          this.dataRules.companyName[0].required = false
        }
        this.dataForm.waterTypeId = ''
        this.dataForm.remarks = ''
        this.dataForm.year = this.ShowYear(0)
        this.dynamicValidateForm.monthsList = []
        this.dynamicValidateForm.monthsList.push({
          month: '',
          water: '',
        })
        this.$nextTick((_) => {
          this.$refs['ruleForm'].resetFields()
        })
      } else {
        this.catWaterDeclareSuperviseByIdReq(item.id)
      }
      this.getAllCompanyReq() // 所有公司
      this.getAllWaterTypeReq() // 用水类型
    },
    getAllCompanyReq() {
      getAllCompany({ page: 1, pageSize: 100 }).then((res) => {
        const { code, data, msg } = res
        if (code !== '0000') return this.$message.error(msg)
        this.companyList = data.list
      })
    },
    getAllWaterTypeReq() {
      getAllWaterType().then((res) => {
        const { code, data, msg } = res
        if (code !== '0000') return this.$message.error(msg)
        this.waterTypeList = data
      })
    },
    // 根据角色id获取公司信息
    async getCompanyInfoByUserIdFun(userId) {
      let result = {}
      const { code, data, msg } = await getCompanyInfoByUserId({ userId })
      if (code !== '0000') return this.$message.error(msg)
      result = { ...data }
      return result
    },
    catWaterDeclareSuperviseByIdReq(id) {
      catWaterDeclareSuperviseById({ id }).then((res) => {
        const { code, data, msg } = res
        if (code !== '0000') return this.$message.error(msg)
        this.disabledActive = true
        this.dataRules.companyName[0].required = false

        this.dataForm.companyId = data.companyId + '' // 公司id
        this.companyNameVal = data.companyName // 公司名称
        this.companyAddress = data.companyAddress // 公司地址

        this.dataForm.waterTypeId =
          data.waterTypeResponse && data.waterTypeResponse.id
        this.companyTypeName = data.companyTypeResponse.companyTypeName
        this.dataForm.remarks = data.remarks
        this.dataForm.year = data.year + ''
        const { insertWaterDeclareItemResponses } = data
        let monthArr = []
        insertWaterDeclareItemResponses.forEach((el) => {
          if (el.water) {
            let obj = {
              id: el.id,
              month: el.month + '',
              water: el.water,
            }
            monthArr.push(obj)
          }
        })
        if (monthArr.length > 0) {
          this.dynamicValidateForm.monthsList = monthArr
        } else {
          // 没有的时候默认显示一条空的
          this.dynamicValidateForm.monthsList = [
            {
              month: '',
              water: '',
            },
          ]
        }
      })
    },
    handleChange(event) {
      let obj
      this.companyList.forEach((el) => {
        if (el.id === event) obj = el
      })
      let { companyAddress, companyTypeResponse } = obj
      this.companyAddress = companyAddress // 公司地址
      this.companyTypeName = companyTypeResponse.companyTypeName // 公司类型
    },
    handleClear() {
      this.companyAddress = ''
      this.companyTypeName = ''
      this.dataForm.companyId = ''
      this.dataForm.companyName = ''
    },
    // 删除季度
    removeMonth(item) {
      var index = this.dynamicValidateForm.monthsList.indexOf(item)
      if (index !== -1) {
        this.dynamicValidateForm.monthsList.splice(index, 1)
      }
    },
    // 添加季度
    addMonth() {
      const monthsLength = this.dynamicValidateForm.monthsList.length
      if (monthsLength > 11) return
      this.dynamicValidateForm.monthsList.push({
        month: '',
        water: '',
      })
    },
    handleSelect(item) {
      this.dataForm.companyId = item.id
      this.companyTypeName = item.companyTypeResponse.companyTypeName
      this.companyAddress = item.companyAddress
    },
    // 提交
    handleSubmit() {
      this.$refs.ruleForm.validate((valid) => {
        if (!valid) return
        if (this.type == 'new') {
          this.dataForm.insertWaterDeclareItemRequest = this.monthFun()
          delete this.dataForm.updateWaterDeclareItemRequest
          delete this.dataForm.id
        } else {
          this.dataForm.updateWaterDeclareItemRequest = this.monthFun()
          delete this.dataForm.insertWaterDeclareItemRequest
        }
        delete this.dataForm.totalWater
        delete this.dataForm.companyName
        const api =
          this.type == 'new'
            ? insertWaterSupervise(this.dataForm)
            : updateWaterSupervise(this.dataForm)
        api.then((res) => {
          const { code, data, msg } = res
          if (code !== '0000') return this.$message.error(msg)
          this.$emit('updata')
          this.dialogVisible = false
        })
      })
    },
    monthFun() {
      const { monthsList } = this.dynamicValidateForm
      // 先判断是否有空值
      const resNull =
        monthsList.length > 1 && monthsList.some((el) => !el.water || !el.month)
      if (resNull) return this.$message.info('您选择的月份或值不能为空')
      //  再判断是否有选择重复的月份
      const resCode = isRepeat(monthsList)
      if (resCode) return this.$message.info('您选择的月份有重复的,请重新选择')
      // 没有填写的月份则需要补齐
      let res = monthData()
      res.forEach((el) => {
        delete el.label
        monthsList.forEach((ele) => {
          if (el.month == ele.month) el.water = ele.water
        })
      })
      return res
    },
  },
}
</script>

<style lang='scss' scoped>
.dataInfo {
  p {
    padding-left: 10px;
    border-left: 4px solid #0079fe;

    span {
      font-size: 18px;
    }
  }
}

.data_info {
  height: 500px;
  overflow: auto;
}
</style>
